//var timer = new Timer("chrono");

function resetDiv(id){
	getDiv(id).innerHTML = '';
	return getDiv(id);
}

function getDiv(id){
	return document.getElementById(id);
}

function createCanvas(id,width,height){
	var canvas = document.createElement("canvas");
	canvas.setAttribute("id",id);
	canvas.setAttribute("width",width);
	canvas.setAttribute("height",height);
	return canvas;
}

function createShape(idDiv,shapeFunction,red,green,blue,id,width){
	if(!width) width = 200;
	try {
		resetDiv(idDiv).appendChild(eval(shapeFunction)(red,green,blue,id,width));
	}
	catch (e){
		resetDiv(idDiv).innerHTML = "Fonction<br/>introuvable";
	}
}

function createShapeFromXHR(xhr){
	destroyErrorMessage();
	var json = JSON.parse(xhr.responseText);
	setShape(json['shape']['shapeName']);
	createShape("left",json['shape']['javascriptFunction'],json['firstColor']['redQuantity'],json['firstColor']['greenQuantity'],json['firstColor']['blueQuantity'],json['firstColor']['colorName']);
	createShape("right",json['shape']['javascriptFunction'],json['secondColor']['redQuantity'],json['secondColor']['greenQuantity'],json['secondColor']['blueQuantity'],json['secondColor']['colorName']);
	setChronoToNow();
}

function setShape(shapeName){
	document.getElementById("shapeName").value = shapeName;
}

function getShape(){
	return document.getElementById("shapeName").value;
}

function manageKeyDown(e){
	//timer.stop();
	if(hasCanvas()){
		switch(e.keyCode){
			case 37 : ajaxLoad("saveTestAnswer",getAnswerData("left"),launchShapeCreation);break;
			case 39 : ajaxLoad("saveTestAnswer",getAnswerData("right"),launchShapeCreation);break;
		}
	}
}

function hasCanvas(){
	return document.getElementById("left").getElementsByTagName("canvas").length >0;
}

function getCanvasId(divId){
	try{
		return document.getElementById(divId).getElementsByTagName("canvas").item(0).id;
	}
	catch (e) {
		return false;
	}
}

function getChrono(){
	return document.getElementById("chrono").innerHTML;
}

function getTimeDifference(){
	return todayDateInMilliseconds() - getChrono();
}

function todayDateInMilliseconds(){
	return new Date().getTime();
}

function setChronoToNow(){
	document.getElementById("chrono").innerHTML = todayDateInMilliseconds();
}

function getCount(){
	return parseInt(document.getElementById("count").innerHTML);
}

function getStepsNumber(){
	return parseInt(document.getElementById("allSteps").innerHTML);
}

function incrCount(){
	document.getElementById("count").innerHTML = getCount() + 1;
}

function getAnswerData(divId){
	var data = "leftColorName="+getCanvasId("left")+"&rightColorName="+getCanvasId("right")+"&shapeName="+getShape()+"&chosenColorName="+getCanvasId(divId)+"&time="+getTimeDifference();
	getDiv("left").innerHTML = "";
	getDiv("right").innerHTML = "";
	return data;
}

function launchShapeCreation(xhr){
	if(getCount() < getStepsNumber()){
		incrCount();
		ajaxLoad("getRandomColoredName",null,createShapeFromXHR);
	}
	else
	{
		ajaxLoad("saveAllAnswers",null,redirectToResults);
	}
}

function redirectToResults(xhr){
	window.location = "index.php?module=results";
}

function redirectToColorTest(){
	window.location = "index.php?module=game";
}

// Fonction permettant de dessiner un diagramme de secteur d'apres les donnees d'un JSON.
// Parametres : json : le JSON contenant toutes les parties du diagramme. Chaque element doit contenir les champs 'redQuantity','greenQuantity' et 'blueQuantity', representant les quantites respectives de rouge, vert et bleu de la couleur avec laquelle il faut remplir cette partie du diagramme, et 'colorName', qui contient le nom de la couleur.
function createPieChart(json,radius){
	// Valeur par defaut du rayon, s'il n'est pas renseigne. Cette valeur sert aussi de coordonnees pour le centre du diagramme.
	if(!radius) radius = 100;
	var data = JSON.parse(json);
	// On cree le canvas qui va contenir le dessin du diagramme.
	var canvas = createCanvas("pieResult",radius*2,radius*2);
	var context = canvas.getContext("2d");
	// Angle de depart de la partie que l'on va dessiner
	var start = 0;
	var i = 0;
	while(i < data.length){
		// On recupere la couleur de la portion en cours
		context.fillStyle = "rgb("+data[i]['redQuantity']+","+data[i]['greenQuantity']+","+data[i]['blueQuantity']+")";
		context.beginPath();
		// On se positionne au centre du diagramme pour que le remplissage se fasse jusqu'au centre.
		context.moveTo(radius,radius);
		var size = 1;
		// On calcule la taille de la portion a dessiner.
		while((i+size) < data.length && data[i]['colorName'] == data[i+size]['colorName']){
			size++;
		}
		// On trace un arc de cercle partant de l'angle de départ, de la taille calculée. 
		context.arc(radius,radius,radius,start,(start+(2*Math.PI/data.length)*size));
		context.fill();
		// On déplace l'angle de départ.
		start += (2*Math.PI/data.length)*size;
		i += size;
		size = 1;
	}
	return canvas;
}

function createCircle(red,green,blue,id,diameter){
	if(!diameter) diameter = 200;
	var radius = diameter / 2;
	var canvas = createCanvas(id,radius*2,radius*2);
	var context = canvas.getContext("2d");
	context.beginPath();
	context.fillStyle = "rgb("+red+","+green+","+blue+")";
	context.arc(radius,radius,radius,0,(Math.PI/180)*360);
	context.fill();
	context.closePath();
	return canvas;
}

function createSquare(red,green,blue,id,side){
	if(!side) side = 200;
	return createRect(red,green,blue,id,side,side);
}

function createRect(red,green,blue,id,width,height){
	if(!width) width = 200;
	if(!height) height = 200;
	var canvas = createCanvas(id,width,height);
	var context = canvas.getContext("2d");
	context.fillStyle = "rgb("+red+","+green+","+blue+")";
	context.beginPath();
	context.moveTo(0, 0);
	context.lineTo(width, 0);
	context.lineTo(width, height);
	context.lineTo(0, height);
	context.closePath();
	context.fill();
	return canvas;
}

function createTriangle(red,green,blue,id,width,height){
	if(!width) width = 200;
	if(!height) height = width;
	var canvas = createCanvas(id,width,height);
	var context = canvas.getContext("2d");
	context.fillStyle = "rgb("+red+","+green+","+blue+")";
	
	context.beginPath();
	context.moveTo(0, height);
	context.lineTo(width, height);
	context.lineTo(width/2, 0);
	context.closePath();
	
	context.fill();
	return canvas;
}